<?php

require_once SHMS_CORE_PATH."/shms_db_cca.inc";
require_once SHMS_CORE_PATH."/shms_db_person.inc";
require_once SHMS_CORE_PATH."/shms_core_common.inc";
require_once SHMS_CORE_PATH."/shms_core_form_cca.inc";

function shms_cca_form_list($form,&$form_state){
  $header = array("Group Name","Chairperson","Email","Options");
  
  $super_access = shms_user_with_super_access();
  global $user;
  $current_user = shms_core_db_load_from_table(SHMS_PERSON_TABLE, 'duid', $user->uid);
  $current_pid = empty($current_user)?0:$current_user['id'];
  
  foreach(shms_core_db_load_assoc_all_match(SHMS_GROUP_TABLE, 'parent_gid', 0, 'id') as $root_id => $root_group){
    $rows = array();
    $gquery = db_select(SHMS_GROUP_TABLE,'g'); $gquery->fields('g');$gquery->condition("parent_gid",$root_id);
    $gquery->isNull('end_time');
    $gquery->innerJoin(SHMS_GROUP_BY_YEAR_TABLE,'gy',"g.id = gy.gid AND gy.year = ".shms_get_current_academic_year());
    $gquery->fields('gy', array('quota','chair_pid'));
    $gquery->innerJoin(SHMS_PERSON_TABLE,'p',"p.id = gy.chair_pid");
    $gquery->addField('p', 'full_name','chair_name');
    $gquery->addField('p', 'personal_email',"chair_email");
    $gquery->addField('p', 'duid','chair_duid');
    foreach($gquery->execute()->fetchAllAssoc("id",PDO::FETCH_ASSOC) as $child_id => $child){
      $rows[] = array(
        $child['name'], $child['chair_name'], $child['chair_email'],
        ($super_access || $child['chair_duid'] == $user->uid)?
        l("Edit",SHMS_CCA_PATH."/".$child['id']."/edit"):"",
      );
    }
    $form[$root_id] = array(
      '#type' => 'fieldset',
      '#title'=> t($root_group['name']),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#children'  => theme("table",array("header"=>$header,"rows"=>$rows)),
    );
  }
  
  return $form;
}

function shms_cca_form_add($form,&$form_state){
  $form = shms_cca_form_get_basic_structure() + shms_cca_form_get_additional_structure();
  shms_core_form_add_submit_button_for_basic($form, 21, "Submit");
  return $form;
}

function shms_cca_parent_form_add($form,&$form_state){
  $form = shms_cca_form_get_basic_structure();
  shms_core_form_add_submit_button_for_basic($form, 21, "Submit");
  return $form;
}

function shms_cca_form_add_validate($form,&$form_state){
  shms_core_cca_validate_chair_matric_and_change_it_to_person_id($form_state);
  shms_core_cca_validate_name_exist($form_state);
  shms_core_cca_validate_quota_field($form_state);
}

function shms_cca_form_add_submit($form,&$form_state){
  $group = $form_state['values'];
  $group += array('start_time'=>time(),'year'=>shms_get_current_academic_year());
  if(shms_core_db_add_group($group))  drupal_set_message("Add Group '".$group['name']."' Succeeded.");
  else drupal_set_message("Adding Group '".$group['name']."' Failed.","error");
}

function shms_cca_parent_form_add_validate($form,&$form_state){
  shms_core_cca_validate_name_exist($form_state);
}

function shms_cca_parent_form_add_submit($form,&$form_state){
  $group = $form_state['values'];
  $group += array( 'parent_gid'=> 0, 'start_time'=>time(), 'cca_assignable'=>0);
  if(shms_core_db_add_group($group))  drupal_set_message("Add Group '".$group['name']."' Succeeded.");
  else drupal_set_message("Adding Group '".$group['name']."' Failed.","error");
}

function shms_cca_form_edit($form,&$form_state,$gid){
  $super_user_access = shms_user_with_super_access();
  $group_raw_data = shms_core_db_cca_load_all($gid);
  $group = $group_raw_data['basic'];
  if(empty($group)){
    drupal_set_message("The Group You're looking for doesn't exist.","error");
    return;
  }
  
  $form = shms_cca_form_get_basic_structure();
  $form['id'] = array("#type"=>"value","#value"=>$gid);
  
  if($group['parent_gid'] != 0){
    $group_this_year = array_shift($group_raw_data['by_year']);
    $group += $group_this_year;
    
    // verify if the editor is the chair-person
    global $user;
    $chair_person = shms_core_db_load_from_table(SHMS_PERSON_TABLE, 'id', $group['chair_pid']);
    $local_user_access = $user->uid == $chair_person['duid'];
    if(!$super_user_access && !$local_user_access){
      drupal_set_message("Sorry you don't have access permission to this page.",'error');
      return array();
    }
  
    $form += shms_cca_form_get_additional_structure();
    $group['chair_pid'] = shms_put_person_str_from_info($chair_person);
    
    $pyid = $group_this_year['id'];
    $form += shms_cca_form_person_in_group_table($pyid);
    $form['update_cca_link'] = array("#markup"=> l("Update CCA Points",SHMS_CCA_PATH."/$pyid/update_cca"),"#weight"=>25);
  } else{ // when dealing with root type
    if(!user_access(SHMSP_PRESIDENT)){
      drupal_set_message("Sorry you don't have access permission to this page.",'error');
      return array();
    }
  }
  
  shms_core_form_add_submit_button_for_basic($form, 8, "Update");
  $form['delete'] = array(
    '#type'   => "submit",
    '#value'  => t("Terminate Group"),
    '#submit' => array('shms_cca_form_delete_group'),
    '#attributes'=> array('onclick'=>"return confirm('Are you sure you want to preceed? This cannot be undone.')"),
    '#weight' => 9,
  );
  shms_add_default_value_for_fields($form, $group,!$super_user_access);
  
  return $form;
}

function shms_cca_form_edit_validate($form,&$form_state){
  shms_core_cca_validate_chair_matric_and_change_it_to_person_id($form_state);
  shms_core_cca_validate_quota_field($form_state);
}

function shms_cca_form_edit_submit($form,&$form_state){
  $group = $form_state['values'];
  
  if(shms_core_db_update_group($group))  drupal_set_message("Update CCA '".$group['name']."' Succeeded.");
  else drupal_set_message("Update Group '".$group['name']."' Failed.","error");
}

function shms_cca_form_add_member($form,&$form_state,$gyid,$type){
  // verify the user's access right first
  if(!shms_cca_form_verify_user_access($form_state,$gyid)){
    drupal_set_message("Sorry user don't have access to this page.","error");
    return array();
  }
  
  if(!isset($form_state['step'])) $form_state['step'] = 'add_member';
  if(!isset($form_state['type'])) $form_state['type'] = $type;
  
  if($form_state['step'] == 'add_member'){
    $form['gid'] = array('#type' => 'value','#value'=>$gyid);
    $header = array("Full Name","Matric No.","Room Number");
    $members = shms_core_db_load_persons_by_blk('all');
    $form_state['member_info'] = $members;  // save the member info for future use
    $form_state['gyid'] = $gyid;            // save the gyid info
    // load the group to get the chair_person
    $group_this_year = shms_core_db_load_from_table(SHMS_GROUP_BY_YEAR_TABLE, 'id', $gyid);
    $blkRows = array();
    
    $current_list = shms_core_db_get_person_info_list_from_gyid($gyid);
    foreach ($members as $pid => $record) {
      // filter out the existing members
      if(array_key_exists($record['pyid'], $current_list))  continue; 
      if($record['id'] == $group_this_year['chair_pid']) continue; // filter out the chair-person
      $blkRows[$record['room_number']{0}][$pid] = array(
        $record['full_name'],$record['matric_no'],$record['room_number'],
      );
    }
    ksort($blkRows);
    foreach($blkRows as $blk_letter => $rows){
      $form[$blk_letter] = array(
        '#type' => "fieldset",
        '#title'=> t("Block ".$blk_letter),
        '#collapsible'  => TRUE,
        '#collapsed'    => FALSE,
        'person'.$blk_letter => array(
          '#type' => "tableselect",
          '#header' => $header,
          "#options"=> $rows,
          '#empty' => t("Sorry There's no residence in this block yet as in the record."),
        ),
      );
    }
    shms_core_form_add_submit_button_for_basic($form, 21, "Confirm");
  } else if($form_state['step'] == "define_position"){
    drupal_set_title("Define Position");
    $member_info = $form_state['member_info'];
      // filter out the 0-valued
    $form_state['member_list'] = array_filter($form_state['member_list']);
    // build the form of member list -> position field
    foreach($form_state['member_list'] as $pid){
      $form["py".$member_info[$pid]['pyid']] = array(
        '#type' => "textfield",
        "#title"=> $member_info[$pid]['full_name'],
        '#field_prefix' => t("Position: "),
        '#required' => TRUE,
      );
    }
    shms_core_form_add_submit_button_for_basic($form, 21, "Save");
  }
  return $form;
}

function shms_cca_form_add_member_validate($form,&$form_state){
  // check if the total number of members exceed the quota.
}

function shms_cca_form_add_member_submit($form,&$form_state){
  if($form_state['step'] == 'add_member'){
    $person_arr = array();
    $values = $form_state['values'];
    
    // build the submitted person array
    foreach($values as $key=>$value){
      if(preg_match("/^person[A-E]$/", $key)) $person_arr += $value;
    }
    $form_state['member_list'] = $person_arr;
    $form_state['rebuild'] = TRUE;
    $form_state['step']  = "define_position";
  } else if($form_state['step'] == 'define_position'){
    $member_form = array(); // 'pyid' => 'position'
    foreach($form_state['values'] as $key=>$position){
      if(substr($key, 0,2) != "py") continue; // filter out the already existed members.
      $member_form[substr($key, 2)] = $position;
    }
    
    // then add person into the group of this year
    shms_core_db_cca_add_member_into_gy($form_state['gyid'],$member_form,$form_state['type']);
    drupal_set_message("These members has been added successfully");
    
    // go back to the edit page.
    $gyinfo = shms_core_db_load_from_table(SHMS_GROUP_BY_YEAR_TABLE, 'id', $form_state['gyid']);
    $form_state['redirect'] = "cca/".$gyinfo['gid']."/edit"; // go back to the edit page
  }
}

function shms_cca_form_update_cca_points($form,&$form_state,$gyid){
  if(!shms_cca_form_verify_user_access($form_state,$gyid)){
    drupal_set_message("Sorry user don't have access to this page.","error");
    return array();
  }
  // firstly load CCA
  $person_infos = shms_core_db_get_person_info_list_from_gyid($gyid);
  $cca_info = shms_core_db_load_from_table(SHMS_GROUP_BY_YEAR_TABLE, 'id', $gyid);
  $form += shms_cca_form_person_in_group_table($gyid,"update_cca") 
         + array("gyid" => array("#type"=>"value","#value" => $gyid))
         + array("back_tbn"=> array("#markup"=>l("Back to Edit Page",SHMS_CCA_PATH."/".$cca_info['gid']."/edit"),"#weight"=>22));
  shms_core_form_add_submit_button_for_basic($form, 21, "Save");
  return $form;
}

function shms_cca_form_update_cca_points_submit($form,&$form_state){
  if(shms_core_db_cca_update_member_info_by_gyid($form_state['values']['member_list'])){
    drupal_set_message(t("CCA points updating succeeds"));
  } else{
    drupal_set_message(t("CCA points updating fails","error"));
  }
  $form_state['rebuilt']  = TRUE;
}

function shms_cca_form_list_type(){
  $header = array("Group Name","Options");
  $rows = array();
  // load form
  foreach(shms_core_db_load_assoc_all_match(SHMS_GROUP_TABLE, 'parent_gid', 0, 'id') as $root_id => $root_group){
    $rows[] = array(
      $root_group['name'], l("Edit",SHMS_CCA_PATH."/".$root_group['id']."/edit"),
    );
  }
  return theme("table",array("header"=>$header,"rows"=>$rows));
}

// update the group info to be terminated, and redirect
function shms_cca_form_delete_group($form,&$form_state){
  $gid = $form_state['values']['id'];
  shms_db_cca_terminate_cca_forever($gid);
  drupal_goto("cca");
  drupal_set_message("CCA has been terminated forever.");
}

function shms_cca_person_form($form,&$form_state){
  // 1. load the pid
  global $user;
  $person = shms_core_db_load_from_table(SHMS_PERSON_TABLE, 'duid', $user->uid);
  if(empty($person)){
    drupal_set_message("Sorry you're not a residence here.","error");
    return array();
  }
  $pid = $person['id'];
  
  // 2. get a list of (pyid,year) pair
  $py_q = db_select(SHMS_PERSON_BY_YEAR_TABLE,"py");
  $py_q->condition("py.pid",$pid); $py_q->fields('py');
  $py_arr = $py_q->execute()->fetchAllAssoc('id',PDO::FETCH_ASSOC);
  
  foreach($py_arr as $pyid=>$record){
    $header = array("CCA Name","My Position","CCA Points");
    $py_cca_query = db_select(SHMS_PERSON_GROUP_TABLE,"pyg");
    $py_cca_query->condition("pyg.pyid",$pyid); $py_cca_query->innerJoin(SHMS_GROUP_BY_YEAR_TABLE,"gy","pyg.gyid = gy.id");
    $py_cca_query->addField("gy", "name","cca_name"); $py_cca_query->fields('pyg',array('id','position_name','cca_points'));
    $py_records = $py_cca_query->execute()->fetchAllAssoc("id",PDO::FETCH_ASSOC);
    $rows = array(); $cca_total = 0;
    foreach($py_records as $py_record){
      $this_cca = $py_record['cca_points'];
      $cca_total += $this_cca;
      $rows[] = array(
        $py_record['cca_name'],
        $py_record['position_name'],
        $this_cca?$this_cca:"Not Awarded Yet",
      );
    }
    
    $form['cca'][$pyid] = array(
      '#type' => "fieldset",
      "#title"=> t("in Year ".$record['year']),
      '#children' => empty($rows)?
        "Sorry you didn't join any CCA in that year.":
        "Current assigned cca points: ".$cca_total.
        theme("table",array("header"=>$header,"rows"=>$rows)),
    );
  }
  
  return $form;
}

